﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Caching;
using log4net;

namespace AgileDashboard
{
    public class Global : HttpApplication
    {
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        protected void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            // configure the logger
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath(Properties.Settings.Default.Log4NetConfigFileLocation)));


            // technique borrowed from: http://aspalliance.com/668
            // add a global cache dependency for pages. If this item is explicitly removed from the cache (programatically), it will purge all page caches
            HttpContext.Current.Cache.Insert(Properties.Settings.Default.GlobalPageCacheKey, DateTime.Now, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            // extra context information attached to each log entry
            // NOTE: This is probably not the most accurate way to store context, due to thread context switching inherent with asp.net
            // see this posting for details: http://comments.gmane.org/gmane.comp.log.log4net.user/1824
            LogicalThreadContext.Properties["USERIP"] = HttpContext.Current.Request.UserHostAddress;
            LogicalThreadContext.Properties["USERAGENT"] = HttpContext.Current.Request.UserAgent;
            LogicalThreadContext.Properties["USERNAME"] = (HttpContext.Current.User != null
                                                               ? HttpContext.Current.User.Identity.Name
                                                               : "ANONYMOUS");

            const string key = "purge";
            if (Request[key] == null) return;
            bool purge;

            if (bool.TryParse(Request[key], out purge))
            {
                // technique borrowed from: http://aspalliance.com/668
                // explicitly remove the global cache dependency for pages. If this item is explicitly removed from the cache (programatically), it will purge all page caches
                HttpContext.Current.Cache.Insert(Properties.Settings.Default.GlobalPageCacheKey, DateTime.Now,
                                                 null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                                                 CacheItemPriority.NotRemovable, null);

            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            if (Log.IsErrorEnabled) Log.Error("ERROR CAUGHT BY GLOBAL: ", Server.GetLastError());


            if (Properties.Settings.Default.PurgeApplicationCacheOnUnhandledErrors)
            {
                if (Log.IsInfoEnabled) Log.Info("Purging application cache after error");
                ClearApplicationCache();
            }
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }


        public void ClearApplicationCache()
        {
            var keys = new List<string>();

            // retrieve application Cache enumerator
            var enumerator = HttpRuntime.Cache.GetEnumerator();

            // copy all keys that currently exist in Cache
            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Key.ToString());
            }

            // delete every key from cache
            foreach (var t in keys)
            {
                HttpRuntime.Cache.Remove(t);
            }
        }
    }
}